package com.zy.ems.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zy.ems.common.util.JsonUtils;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.common.util.TokenUtils;
import com.zy.ems.utils.enums.Constant;
import com.zy.ems.utils.enums.UserTypeEnum;
import com.zy.ems.utils.exceptions.UserCode;

public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = StringUtils.parseStr(req.getRequestURI());

        // 过滤登录URI
        if (uri.indexOf(Constant.DOLOGIN) != -1 || uri.indexOf("html") != -1) {
            chain.doFilter(request, response);
            return;
        }

        String userId = StringUtils.parseStr(req.getParameter(Constant.USERID));
        String mobile = StringUtils.parseStr(req.getParameter(Constant.MOBILE));
        String token = StringUtils
                .parseStr(req.getParameter(Constant.ACCESS_TOKE));

        boolean access = TokenUtils.checkToken(userId, mobile, token,
                UserTypeEnum.USER);

        if (!access) {
            Object data = ResultTool.error(UserCode.B_USER_2005);
            String msg = JsonUtils.writeObject2JSON(data);
            res.getOutputStream().write(msg.getBytes());
        }else{
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }

}
